package com.beemans.common.ext.glide

import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target

/**
 * @author tiamosu
 * @date 2021/4/8.
 */
class GlideRequestListener<T>(
    private val glideCallback: GlideCallback<T>
) : RequestListener<T> {

    override fun onLoadFailed(
        e: GlideException?,
        model: Any?,
        target: Target<T>?,
        isFirstResource: Boolean
    ): Boolean {
        glideCallback.onFail?.invoke(e, model, target, isFirstResource)
        return false
    }

    /**
     * [android.widget.ImageView] 在布局内必须指定具体宽高，或者可能导致[onResourceReady]回调失败！！！
     */
    override fun onResourceReady(
        resource: T,
        model: Any?,
        target: Target<T>?,
        dataSource: DataSource?,
        isFirstResource: Boolean
    ): Boolean {
        if (resource is GifDrawable) {
            resource.setLoopCount(GifDrawable.LOOP_FOREVER)
        }
        glideCallback.onSuccess?.invoke(resource, model, target, dataSource, isFirstResource)
        return false
    }
}